<?php
  // icecast.inc
  // Dial Radio Control System
  //     Icecast interop functions
  // June 10, 2010

class Icecast {
    
    public static function getStatus() {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, DIAL_ICECAST_ADMINSTATS);
        curl_setopt($ch, CURLOPT_USERPWD, DIAL_ICECAST_USERWPD);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($ch);
        curl_close($ch);
        if(!$data) {
            throw new Exception("Can't connect to Icecast Server!");
        }
        $xml = new SimpleXMLElement($data);
        return $xml;
    }
    
    public static function isUp() {
        try {
            self::getStatus();
        } catch (Exception $e) {
            return false;
        }
        return true;
    }
    
    public static function uptime() {
        $xml = self::getStatus();
        $timestamp = strtotime($xml->server_start);
        $now = time();
        
        $difference = $now - $timestamp;
        
        // Ruthlessly stolen from http://www.phpbuilder.com/board/showthread.php?t=10100466
        
        $days = 0; $hours = 0; $minutes = 0; $seconds = 0;
        
        $time_increments = array(
            'Days' => 86400,
            'Hours' => 3600,
            'Minutes' => 60,
            'Seconds' => 1 );
        
        // will hold our values for ( day, minute, hour, seconds )
        $time_span = array();
        
        // cycle through time_increments 
        while( list( $key, $value ) = each( $time_increments )) {
        $this_value = (int) ( $difference / $value );
        $difference = ( $difference % $value );
        
        // Make the values look like Liquidsoap's uptime.
        if ($this_value < 10 && $key != 'Days') { $this_value = '0' . $this_value; };
        $time_span[$key] = $this_value;
        }
        
        return "{$time_span['Days']}d {$time_span['Hours']}h {$time_span['Minutes']}m {$time_span['Seconds']}s";
    }
}